package org.linlinjava.litemall.core.storage;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.InputStream;

@Component
public class AliStorage {

    private static final Logger logger = LoggerFactory.getLogger(AliStorage.class);

    @Value("${litemall.storage.aliyun.endpoint}")
    private String endpoint ;

    @Value("${litemall.storage.aliyun.accessKeyId}")
    private String accessKeyId ;

    @Value("${litemall.storage.aliyun.accessKeySecret}")
    private String accessKeySecret ;

    private OSS oss ;

    @PostConstruct
    public void init(){
        oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        for (Bucket bucket : Bucket.values()) {
            if (!oss.doesBucketExist(bucket.getBucketName())){
                oss.createBucket(bucket.getBucketName());
                logger.info("[AliStorage] create bucket :{}", bucket.getBucketName());
            }
        }
    }


    public String store(InputStream inputStream, String filename, String bucketName){
        logger.info("[AliStorage] store file by inputstream fileName:{}, bucketName:{}", filename, bucketName);
        String key = buildKey(filename);
        PutObjectResult putObjectResult = oss.putObject(bucketName, key, inputStream);
        logger.info("[AliStorage] store file result :{}", putObjectResult);
        return "https://" + bucketName + "." + endpoint + "/" + key ;
    }

    private String buildKey(String fileName){
        return System.currentTimeMillis() + fileName;
    }

    public static enum Bucket {
        shopMobilePhoto("shop-mobile-photo", "shop-mobile-photo"),
        shopFile("shop-mobile-file", "shop-mobile-photo");

        private String bucketName ;

        private String prefix ;

        Bucket(String bucketName, String prefix) {
            this.bucketName = bucketName;
            this.prefix = prefix;
        }

        public String getBucketName() {
            return bucketName;
        }

        public void setBucketName(String bucketName) {
            this.bucketName = bucketName;
        }

        public String getPrefix() {
            return prefix;
        }

        public void setPrefix(String prefix) {
            this.prefix = prefix;
        }


    }

}
